import axios from 'axios';
import { BASE_API, PROD_URL, SUCCESS, FORBIDDEN } from './conf';
import store from '../store';
import router from '../router';
import { AlertModule } from 'vux';

const service = axios.create({
  baseURL: process.env.NODE_ENV == 'development' ? BASE_API : PROD_URL,
  timeout: 5000
});

service.interceptors.request.use(
  config => {
    // const reqToken = store.getters['common/token'];
    const reqToken = localStorage.getItem('accessToken');
    if (reqToken) {
      config.headers['Access-Token'] = reqToken;
    }
    // config.headers['content-type'] = 'application/x-www-form-urlencoded';
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const data = response.data;
    if (data.code === SUCCESS) {
      const resHeaders = response.headers;
      if (resHeaders['access-token']) {
        localStorage.setItem('accessToken', resHeaders['access-token'])
        // store.dispatch('common/setAccessToken', resHeaders['access-token']);
      }
    } else if (data.code === FORBIDDEN) {
      AlertModule.show({
        title: '提示',
        content: '未登录，请登陆后继续访问！',
        onHide () {
          router.replace({ path: '/login' });
        }
      });
      return false;
    } else {
      AlertModule.show({
        title: '提示',
        content: `${data.msg}` || '服务器繁忙，请稍后尝试！'
      });
      return false;
    }
    return data;
  },
  error => {
    console.log(`err${error}`);
    AlertModule.show({
      title: '提示',
      content: '服务器繁忙，请稍后尝试！'
    });
    return Promise.reject(error);
  }
);

export default service;
